package com.xunmall.gateway.interceptor;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.xunmall.base.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.net.URL;

/**
 * Fouction : 用于部署后的验证，可指定需要访问的banbu服务地址
 */
@Slf4j
public class DebugRouteZuulFilter extends ZuulFilter {

	@Override
	public String filterType() {
		return "route";
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
    public boolean shouldFilter() {
		return true;
	}

	@Override
    public Object run() {

		RequestContext ctx = RequestContext.getCurrentContext();

		try {
//			System.out.println("=======================================");
//			Enumeration headerNames = ctx.getRequest().getHeaderNames();
//			while (headerNames.hasMoreElements()) {
//				String key = (String) headerNames.nextElement();
//				String value = ctx.getRequest().getHeader(key);
//				System.out.println(key + ":" + value);
//			}

			String host = ctx.getRequest().getHeader("banbu-server");
			if(StringUtils.isNotEmpty(host)) {
				String serviceId = (String)ctx.get("serviceId");
				if(StringUtils.equalsIgnoreCase(serviceId, "banbu-v3")) {
					URL url = new URL("http://" + host);
					ctx.setRouteHost(url);
//					log.info("Request reroute to " + url.toString());
				}
			}

		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return null;
	}
}